<template>
  <transition name="opacity">
    <dialog v-show="visible" ref="myMessageRef" :class="`my-message ${typeClass}`" @click="hidden">
      <span v-html="props.content"></span>
    </dialog>
  </transition>
</template>

<script>
export default { name: 'Message' };
</script>
<script setup>
import { computed, nextTick, onMounted, ref } from 'vue';

const props = defineProps({
  type: {
    type: String,
    default: 'primary',
    validator: function (value) {
      return ['primary', 'success', 'warning', 'error'].includes(value);
    }
  },
  content: {
    type: String,
    default: '---'
  },
  delay: {
    type: Number,
    default: 3000
  }
});

const myMessageRef = ref();
const typeClass = computed(() => `my-message-${props.type}`);
const visible = ref(false);
const timer = ref(null);
onMounted(() => {
  // 从 hidden 到 show 才会触发<transition>
  nextTick(() => {
    visible.value = true;
    myMessageRef.value.show();
  });

  // 销毁节点前改变显示状态
  clearTimeout(timer.value);
  timer.value = setTimeout(() => {
    hidden();
  }, props.delay - 300);
});

const hidden = () => {
  clearTimeout(timer.value);
  visible.value = false;
  if (myMessageRef.value) {
    myMessageRef.value.close();
  }
};
</script>

<style lang="scss" scoped>
.my-message {
  top: 40px;
  display: flex;
  justify-content: center;
  min-width: 240px;
  color: #222222;
  text-align: center;
  padding: 12px 24px;
}

.my-message-primary {
  background-color: var(--primary-color-message);
  border: 1px solid var(--primary-color);
  border-radius: 4px;
  box-shadow: 0 0 10px -4px var(--primary-color);
}

.my-message-success {
  background-color: var(--success-color-message);
  border: 1px solid var(--success-color);
  border-radius: 4px;
  box-shadow: 0 0 10px -4px var(--success-color);
}

.my-message-warning {
  background-color: var(--warning-color-message);
  border: 1px solid var(--warning-color);
  border-radius: 4px;
  box-shadow: 0 0 10px -4px var(--warning-color);
}

.my-message-error {
  background-color: var(--error-color-message);
  border: 1px solid var(--error-color);
  border-radius: 4px;
  box-shadow: 0 0 10px -4px var(--error-color);
}
</style>
